﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entities;
using Interfaces;
using Utilites;
using DAOBase;

namespace Repository
{
    public class UserRepository : IRepository<User>
    {
        private SmartDictionary users = new SmartDictionary(
            (id) => { return user_dao.LoadUser(id); }
            );

        private static IUserDAO user_dao;
        public UserRepository()
        {
            var facade = new DAOFacade();
            if (user_dao == null)
                user_dao = facade.GetFactory().GetUserDAO();
        }

        public SmartDictionary GetAllObjects()
        {
            return users;
        }

        public void InsertObject(User obj)
        {
            users[obj.ID] = obj;
            obj.State = EntityState.New;
        }

        public int GetUserID(string login)
        {
            return user_dao.GetUserID(login);
        }

        public bool UserExists(int id)
        {
            return user_dao.UserExists(id);
        }

        public bool UserExists(string login)
        {
            return user_dao.UserExists(login);
        }

        public void DeleteObject(User obj)
        {
            users[obj.ID].State = EntityState.Deleted;
        }

        public void Go()
        {
            foreach (var rec in users)
            {
                switch(rec.State)
                {
                    case EntityState.New: user_dao.InsertUser((User)rec);
                        break;
                    case EntityState.Modified: user_dao.ModifyUser((User)rec); break;
                    case EntityState.Deleted: user_dao.RemoveUser((User)rec); break;
                }
                rec.State = EntityState.Unchanged;
            }
        }

        public void Reload()
        {
            foreach (var rec in users)
            {
                users[rec.ID] = user_dao.LoadUser(rec.ID);
            }
        }

        public void OnTimerUpdateInvoked(object sender, EventArgs e)
        {
            Reload();
        }
    }
}
